package com.xiaocg.base.juc;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author xiaocg
 * 信号量
 */
public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);
        for (int i = 0; i < 6; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println("当前线程:"+Thread.currentThread().getName()+"来了");
                    TimeUnit.SECONDS.sleep(new Random().nextInt(5));
                    System.out.println("当前线程:"+Thread.currentThread().getName()+"走了");
                }catch (Exception e){
                }finally {
                    semaphore.release();
                }

            }).start();
        }
    }
}
